package com.gzy.studentsociety.web;

import com.gzy.studentsociety.dao.SocietyDao;
import com.gzy.studentsociety.dao.SocietyDaoImpl;
import com.gzy.studentsociety.dao.StudentDao;
import com.gzy.studentsociety.dao.StudentDaoImpl;
import com.gzy.studentsociety.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(name = "student",urlPatterns = "/student/*")
public class StudentServlet extends RouteServlet {
    private StudentDao studentDao = new StudentDaoImpl();

    @Override
    protected Class getMyClass() {
        return this.getClass();
    }
    public String login(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        Student stu = null;

        try {
            stu = studentDao.login(account,password);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
            handleException(throwables,req, res);
        }

        if (stu != null){
            HttpSession session = req.getSession();
            session.setAttribute("student",stu.getStudentNumber());
            res.sendRedirect("/studentSociety/society/mainIndex");
        }else{
            req.getRequestDispatcher("/index.jsp?message=account or password is wrong").forward(req,res);
        }
        return "direct";
    }
}
